<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { message } from "@/utils/message";
import type { ElTreeV2 } from "element-plus";
import { extractPathList, deleteChildren } from "@/utils/tree";
import { getAsyncRoutes } from "@/api/routes";

const dataProps = ref({
  value: "uniqueId",
  children: "children"
});

const treeRef = ref<InstanceType<typeof ElTreeV2>>();

const menusData = ref([]);

const expandedKeys = extractPathList(menusData.value);

async function onAsyncRoutes() {
  getAsyncRoutes().then(({ data }) => {
    menusData.value = deleteChildren(data);
  });
}

onMounted(() => {
  onAsyncRoutes();
});

const formVisible = ref(false);
const closeDialog = () => {
  formVisible.value = false;
};

const submitMenu = () => {
  message("提交成功", { type: "success" });
  formVisible.value = false;
};

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => {
      return {};
    }
  }
});

const emit = defineEmits(["update:visible", "add-up-search"]);
watch(
  () => formVisible.value,
  val => {
    emit("update:visible", val);
  }
);

watch(
  () => props.visible,
  val => {
    formVisible.value = val;
  }
);
</script>

<template>
  <el-dialog
    v-model="formVisible"
    title="分配菜单"
    :width="680"
    draggable
    :before-close="closeDialog"
  >
    <el-tree-v2
      ref="treeRef"
      :data="menusData"
      :props="dataProps"
      show-checkbox
      :height="380"
      :default-expanded-keys="expandedKeys"
    >
      <template #default="{ data }">
        <span>{{ data.meta.title }}</span>
      </template>
    </el-tree-v2>

    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="submitMenu"> 确定 </el-button>
    </template>
  </el-dialog>
</template>
